package com.epfresh.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.epfresh.R;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.City;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.User;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.NetworkUtil;
import com.epfresh.api.widget.tablayout.CommonTabLayout;
import com.epfresh.api.widget.tablayout.TabEntity;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.basedialog.*;
import com.epfresh.bean.CityAddress;
import com.epfresh.bean.CityAddressBox;
import com.epfresh.bean.GoodsParameters;
import com.epfresh.fragment.CartFragment;
import com.epfresh.fragment.CategoryGoodsFragment;
import com.epfresh.fragment.HomeFragment;
import com.epfresh.fragment.HomeFragmentNew;
import com.epfresh.fragment.MineFragment;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.DataManager;
import com.epfresh.location.LocationService;
import com.epfresh.utils.FileCache;
import com.epfresh.views.dialog.OnFilterClickListener;
import com.epfresh.views.dialog.ProductCategoryDialog;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class HomeActivity extends BaseActivity implements OnTabSelectListener, DataManager.OnCartCountChangeListener {

    private CommonTabLayout lyTab;

    //    private HomeFragment homeFragment;
    public HomeFragmentNew homeFragment;
    private CartFragment cartFragment;
    //    private CategoryGoodsFragment goodsFragment;
    private MineFragment mineFragment;

    public int currentIndex = 0;

    private String TAG_HOME_FRAGMENT = "homeFragment";
    private String TAG_CATEGORY_FRAGMENT = "goodsFragment";
    private String TAG_CART_FRAGMENT = "cartFragment";
    private String TAG_MINE_FRAGMENT = "mineFragment";

    public LocationService locationService;

    @Override
    protected View getToolBar() {


        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("refresh", "fresh often");

        ApplicationHelper.getInstance().isHomeActivityAlive = true;
        if (homeFragment != null && DataManager.getInstance().bindStoreReFresh) {
            DataManager.getInstance().bindStoreReFresh = false;
//            homeFragment.reFreshTopFragmentStore();todo
        } else {
            if (homeFragment != null && DataManager.getInstance().oftenListReFresh) {
                DataManager.getInstance().oftenListReFresh = false;
//                homeFragment.reFreshTopFragment();todo
            }
        }
        if (mineFragment != null) {
            mineFragment.mHttpOrderHint();
        }
//        if (cartFragment != null) {
//            cartFragment.onRefreshCart();
//        }
    }

    public void reFreshStore() {
        if (homeFragment != null && DataManager.getInstance().bindStoreReFresh) {
            DataManager.getInstance().bindStoreReFresh = false;
//            homeFragment.reFreshTopFragmentStore();todo
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        if (NetworkUtil.isWifi(this)) {
            MobclickAgent.onEvent(HomeActivity.this, "Check_Network_WIFI");
        } else if (NetworkUtil.isMobile(this)) {
            MobclickAgent.onEvent(HomeActivity.this, "Check_Network_WWAN");
        }
        updateUserProfile();
        if (savedInstanceState != null) {
            int currentIndex = savedInstanceState.getInt("currentIndex");
            getIntent().putExtra("home_tab_index", currentIndex);

            Fragment f = getSupportFragmentManager().findFragmentByTag(TAG_HOME_FRAGMENT);
            if (f != null)
//                homeFragment = (HomeFragment) f;todo
                homeFragment = (HomeFragmentNew) f;
//            f = getSupportFragmentManager().findFragmentByTag(TAG_CATEGORY_FRAGMENT);
            if (f != null)
//                goodsFragment = (CategoryGoodsFragment) f;
                f = getSupportFragmentManager().findFragmentByTag(TAG_CART_FRAGMENT);
            if (f != null)
                cartFragment = (CartFragment) f;
            f = getSupportFragmentManager().findFragmentByTag(TAG_MINE_FRAGMENT);
            if (f != null)
                mineFragment = (MineFragment) f;
        }
        initLocation();

        ApplicationHelper.getInstance().isHomeActivityAlive = true;
        ApplicationHelper.getInstance().updateVersion(false, null);
        ApplicationHelper.getInstance().expiredTime();
        initView();
    }

    public void updateUserProfile() {
        String token = getUser().getAccess_token();
        if (token == null || "".equals(token)) {
            return;
        } else {
            RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
            data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_profile);
            //data.setToken(getUser().getToken());
            Map<String, String> map = new HashMap<>();
            map.put("accountId", getUser().getAccountId());
            data.setParameters(map);
            request(data, AppPurchaseRouterConstant.cmd_account_acc_profile, onRequestListener);
        }
    }

    OnRequestListener<User> onRequestListener = new OnRequestListener<User>() {
        @Override
        public User jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, User.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<User> response, Object tag) {
            User user = response.getResponseElement();
            if (user == null) {
                return;
            }
            user.setAccess_token(getUser().getAccess_token());
            user.setAccountId(getUser().getAccountId());
            user.setPassword(getUser().getPassword());
            user.setTag(UUID.randomUUID().toString());
            updateUser(user);
        }
    };


    public static boolean isLogin;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String from = intent.getStringExtra("from");
        if (from != null) {
            if (from.equals("marketGoodsFragment") || from.equals("searchGoodsActivity")) {
                onTabSelect(1);
            }
        }
        String refreshFlag = intent.getStringExtra("refreshFlag");
        if (refreshFlag != null) {
            if (refreshFlag.equals("refreshHomeFrag")) {
                if (homeFragment != null) {
                    homeFragment.refresh();
                }
            }
            if (refreshFlag.equals("refreshHomeCart")) {
                if (cartFragment != null) {
                    cartFragment.refresh();
                }
            }
        }
        if (homeFragment == null) {
//            homeFragment = new HomeFragment();todo
            homeFragment = new HomeFragmentNew();
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            transaction.add(R.id.content, homeFragment, TAG_HOME_FRAGMENT);
        }
        int index = intent.getIntExtra("home_tab_index", -1);
/*        int preferenceFlag = intent.getIntExtra("preference_flag", -1);
        if(preferenceFlag == 1){
            goodsFragment = null;
            homeFragment = null;
            cartFragment = null;
        }*/

        if (index > -1 && index < 3) {
            onTabSelect(index);
//            lyTab.setCurrentTab(index);
            updatePageStatus(index);
            currentIndex = index;
            if (cartFragment != null) {
                cartFragment.updateBtnStatus();
            }
            if (index == 2 && mineFragment != null) {
                mineFragment.updateUserProfile();
            }
            /*
            有关退出登录的逻辑，是退出后到达首页_首页；刷新现有页面信息；
            setActivity中做以上操作；传参如下：
            main.putExtra("home_tab_index",0);
            main.putExtra("type",1);
             */
            int type = intent.getIntExtra("type", -1);
            if (type == 1) {
//                homeFragment.requestHome(ApplicationHelper.getInstance().getCity().getCityId(), ApplicationHelper.getInstance().getCity().getCityName(), null, null,true);todo
                return;
            }


            //注销之后返回,没有登陆
            int reType = intent.getIntExtra("re_type", -1);

            isLogin = intent.getBooleanExtra("isLogin", false);
            //如果退出登陆,刷新散货待采店铺
            if (isLogin && homeFragment != null) {
//                homeFragment.reLoginBack();todo
            }
            if (reType == 1) {

                if (cartFragment != null) {
                    getSupportFragmentManager().beginTransaction().remove(cartFragment);
                    cartFragment = null;
                }

                if (mineFragment != null) {
                    getSupportFragmentManager().beginTransaction().remove(mineFragment);
                    mineFragment = null;
                }
                getSupportFragmentManager().beginTransaction().commit();
                DataManager.getInstance().isNeedRefreshCart = true;
                DataManager.getInstance().setCartCnt(0);
                DataManager.getInstance().clearCart();
                onCartCountChange(0);

            }
        }
        String cityId = intent.getStringExtra("cityId");
        String cityName = intent.getStringExtra("cityName");
        String lng = intent.getStringExtra("lng");
        String lat = intent.getStringExtra("lat");
        if (index == 0) {
            if (cityId != null && !"".equals(cityId)) {
                homeFragment.reqHome(cityId, lng, lat);
            } else {
                City city = ApplicationHelper.getInstance().getCity();
                if (city != null) {
                    cityId = city.getCityId();
                    cityName = city.getCityName();
                }
                if (cityId != null && !"".equals(cityId)) {
                    homeFragment.reqHome(cityId, lng, lat);
                }
            }
        }
    }

    public void updateCategory() {
//        if (goodsFragment != null) {
//
//            goodsFragment.updateData(false);
//        }

        if (cartFragment != null) {
            cartFragment.onRefreshCart();
        }
    }

    public void toolbarStyle(boolean isDarkColor) {
        if (isDarkColor) {
            actionbar.setBackgroundResource(R.color.colorPrimary);
        } else {
            actionbar.setBackgroundResource(R.color.colorPrimary);
        }
    }

    private void initView() {

        String[] mTitles = {getString(R.string.home_page),
//                getString(R.string.category_page),
                getString(R.string.cart_page),
                getString(R.string.mine_page)
        };
        int[] mIconUnSelectIds = {
                R.mipmap.tab_home_unselect,
//                R.mipmap.tab_category_unselect,
                R.mipmap.tab_cart_unselect,
                R.mipmap.tab_mine_unselect};
        final int[] mIconSelectIds = {
                R.mipmap.tab_home_select,
//                R.mipmap.tab_category_select,
                R.mipmap.tab_cart_select,
                R.mipmap.tab_mine_select};
        ArrayList<TabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }
        lyTab = (CommonTabLayout) findViewById(R.id.ly_navigation);
        lyTab.setTabItemRes(R.layout.layout_tab_top);
        lyTab.setTabData(mTabEntities);
        lyTab.setMsgMargin(1, LocalDisplay.dp2px(-10), 0);
        lyTab.setOnTabSelectListener(this);

        int index = getIntent().getIntExtra("home_tab_index", 0);
        if (index > -1 && index < 3) {
            lyTab.setCurrentTab(index);
            updatePageStatus(index);
            currentIndex = index;
        }


        DataManager.getInstance().registerMsgView("home_activity", this);

        DataManager.getInstance().updateCartCnt();

    }

    public View getCartView() {
        return lyTab.getIconView(1);
    }

    public ViewGroup getMainView() {
        return (ViewGroup) findViewById(R.id.rl_main_layout);
    }

    public int cartCount;

    @Override
    public void onCartCountChange(int count) {
        cartCount = count;
//        homeFragment.showGoCartRed(cartCount >0,false);todo
        if (count > 0) {
            lyTab.showMsg(1, count);
            if (homeFragment != null) {
                homeFragment.setOftenTitleHasRedTip(true);
            }
        } else {
            if (homeFragment != null) {
                homeFragment.setOftenTitleHasRedTip(false);
            }
            lyTab.hideMsg(1);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("currentIndex", currentIndex);

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onTabSelect(int i) {
        lyTab.setCurrentTab(i);

//        if (cartFragment != null) {
//            cartFragment.updateBtnStatus();
//        }

        if (i > 0 && (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token()))) {
            lyTab.setCurrentTab(currentIndex);
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra("home_tab_index", i);
            startActivity(intent);
        } else {
            if (i == 0) {
                Log.e("redandnumber", "" + (cartCount > 0));
                if (homeFragment != null) {
                    if (isLogin) {
                        City city = ApplicationHelper.getInstance().getCity();
                        if (city != null) {
                            String cityId = city.getCityId();
                            if (!TextUtils.isEmpty(cityId)) {
                                homeFragment.reqHome(cityId, null, null);
                            }
                        }
                        isLogin = false;
                    }
//                    homeFragment.showGoCartRed(cartCount > 0, true);todo
                    if (DataManager.getInstance().oftenListReFresh) {
                        DataManager.getInstance().oftenListReFresh = false;
//                        homeFragment.reFreshTopFragment();todo
                    }
                }
            }
            currentIndex = i;
            updatePageStatus(i);
//            if( i == 1 && goodsFragment != null){
//                goodsFragment.updateCount();
//            }else

            if (i == 1 && cartFragment != null) {
                Log.e("onStart", "car onRefreshCart");

                cartFragment.onRefreshCart();
            }/*else if(i==0 && homeFragment != null && ApplicationHelper.getInstance().getUser().getToken() != null){
                homeFragment.reFreshTopFragment();
            }*/
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 0x0303) {
            freshAllGoods();
//            if(homeFragment!=null)
//                homeFragment.reFreshTopFragment();todo
        }
    }

    public void freshAllGoods() {
//        if(goodsFragment !=null&& goodsFragment.cgDelegate!=null)
//            goodsFragment.cgDelegate.refresh(true);
    }


    @Override
    public void onTabReselect(int i) {
        if (i == 2 && mineFragment != null && (ApplicationHelper.getInstance().getUser().getAccess_token() != null && !"".equals(ApplicationHelper.getInstance().getUser().getAccess_token()))) {
            mineFragment.updateUserProfile();
        }
    }

    private void updatePageStatus(int i) {
        FragmentManager fm = getSupportFragmentManager();

        FragmentTransaction transaction = fm.beginTransaction();

        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
//        if (goodsFragment != null) {
//            transaction.hide(goodsFragment);
//        }
        if (cartFragment != null) {
            transaction.hide(cartFragment);
        }
        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }
        if (i == 0) {
            if (homeFragment == null) {
//                homeFragment = new HomeFragment();todo
                homeFragment = new HomeFragmentNew();
                transaction.add(R.id.content, homeFragment, TAG_HOME_FRAGMENT);
            }
            transaction.show(homeFragment);
        }
//        else if (i == 1) {
//            if (goodsFragment == null) {
//                goodsFragment = new CategoryGoodsFragment();
//                transaction.add(R.id.content, goodsFragment, TAG_CATEGORY_FRAGMENT);
//            }
//            transaction.show(goodsFragment);
//
//        }
        else if (i == 1) {
            if (cartFragment == null) {
                cartFragment = new CartFragment();
                transaction.add(R.id.content, cartFragment, TAG_CART_FRAGMENT);
            }
            transaction.show(cartFragment);

        } else if (i == 2) {
            if (mineFragment == null) {
                mineFragment = new MineFragment();
                transaction.add(R.id.content, mineFragment, TAG_MINE_FRAGMENT);
            }
            transaction.show(mineFragment);
        }
        transaction.commit();
    }

    private long exitTime = 0; // 系统退出时间

    @Override
    public void onBackPressed() {
        findViewById(R.id.ll_keyboard).setVisibility(View.GONE);
        findViewById(R.id.v_keyboard_bg).setVisibility(View.GONE);
        boolean isReturn = false;
//        if (homeFragment != null && homeFragment.pop != null && homeFragment.pop.isShowing()) {
//            homeFragment.pop.dismiss();
//            isReturn = true;
//        }todo

//        if (goodsFragment != null && goodsFragment.isCategoryDialogShow()) {
//            goodsFragment.dismissCategoryDialog();
//            isReturn = true;
//        }


//        if (filterDialog != null && filterDialog.isShowing()) {
//            if (filterDialog.isCategoryMoreShowing()) {
//                filterDialog.dismissCategoryMore();
//            } else
//                filterDialog.dismiss();
//            isReturn = true;
//        }

        if (productCategoryDialog != null && productCategoryDialog.isShowing()) {
            productCategoryDialog.dismiss();
            isReturn = true;
        }

        if (isReturn) {
            return;
        }

        if (lyTab.getCurrentTab() != 0) {
            updatePageStatus(0);
            lyTab.setCurrentTab(0);
            return;
        }
        if (System.currentTimeMillis() - exitTime > 2000) {
            toast("再按一次返回键，退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }

    ProductCategoryDialog productCategoryDialog;

    public void openProductCategory(String marketId, GoodsParameters parameters, OnFilterClickListener onFilterClickListener) {

        if (productCategoryDialog == null) {
            productCategoryDialog = new ProductCategoryDialog(this);
        }

        productCategoryDialog.setMarketId(marketId);
        productCategoryDialog.setParameters(parameters);
        productCategoryDialog.setOnFilterClickListener(onFilterClickListener);
        productCategoryDialog.show();
        productCategoryDialog.updateCategory();
    }


//    ProductFilterDialog filterDialog;
//
//    public void openFilterDialog(String marketId, GoodsParameters parameters, OnFilterClickListener onFilterClickListener) {
//
//
//        if (filterDialog == null) {
//            filterDialog = new ProductFilterDialog(this);
//        }
//
//        filterDialog.setOnFilterClickListener(onFilterClickListener);
//        filterDialog.setMarketId(marketId);
//        filterDialog.setParameters(parameters);
//        filterDialog.show();
//        requestCategoryFilter();
//    }
//
//    private OnRequestListener<FilterCategory> onRequestFilterListener = new OnRequestListener<FilterCategory>() {
//        @Override
//        public FilterCategory jsonToObj(String s) {
//            return new Gson().fromJson(s, FilterCategory.class);
//        }
//
//        @Override
//        public void onFail(int i, Object o, Object o1) {
//            filterDialog.showErrorView();
//        }
//
//        @Override
//        public void onResponseError(int i, Object o, Object o1) {
//
//            filterDialog.showErrorView();
//        }
//
//        @Override
//        public void onStart(Object o) {
//
//            filterDialog.showLoadView();
//        }
//
//        @Override
//        public void onResponse(ResponseEntity<FilterCategory> responseEntity, Object o) {
//            FilterCategory responseElement = responseEntity.getResponseElement();
//
//            if (responseElement != null) {
//                filterDialog.showContentView();
//
//                filterDialog.initStatus(responseElement);
//            }
//        }
//    };
//
//    public void requestCategoryFilter() {
//        RequestEntity re = new RequestEntity();
//        re.setCmd("product/conditions");
//        requestDc(re, "product/conditions", onRequestFilterListener);
//    }


    @Override
    public void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
/*        if (homeFragment != null) {
            homeFragment.finishTimer();
        }*/
        super.onStop();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
/*        if (homeFragment != null) {
            if (!homeFragment.isRequestHome) {
                homeFragment.requestDc();
            }
           // homeFragment.showTimer();
        }*/

    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        locationService.registerListener(mListener);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
    }


    @Override
    protected void onDestroy() {
        ApplicationHelper.getInstance().isHomeActivityAlive = false;
        DataManager.getInstance().removeMsgView("home_activity");
        super.onDestroy();
    }

    //记录当前位置
    private CityAddressBox locationBox = new CityAddressBox();

    //开通城市列表
    CityAddress cityOpenList;
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            Log.e("city", "onReceive");
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                String city = location.getCity();
                String province = location.getProvince();
                String cityCode = location.getCityCode();

                Log.e("city", "province:" + province + "");
                Log.e("city", "city:" + city + "");
                Log.e("city", "citycode:" + cityCode + "");
                if (builder != null) {
                    return;//每次启动只加载一次对话框
                }
                if (city.equals(ApplicationHelper.getInstance().getCity().getCityName())) {
                    return;//当前定位及当前所选城市
                }
                if (province.equals(ApplicationHelper.getInstance().getCity().getCityName())) {
                    return;//当前定位在当前所选省内
                }
                String cityId = getLocationCityId(city, province);
                if (cityId == null) {
                    return;//当前城市未开通
                }
                locationBox.setCityName(city);
                locationBox.setCityId(cityId);
                locationBox.setLocation(city);
                showSwitch();
            }
        }
    };

    private String getLocationCityId(String cityName, String province) {
        FileCache fileCache = new FileCache(mContext);
        if (cityOpenList == null) {
            String flag = fileCache.readFile(fileCache.getCachePath() + "epfresh_open_area_data.txt");
            if (fileCache.readFile(fileCache.getCachePath() + "epfresh_open_area_data.txt") != null) {
                cityOpenList = new Gson().fromJson(flag, CityAddress.class);
            } else {
                return null;
            }
        }
        if (locationBox != null && cityOpenList != null && ((cityName != null && !"".equals(cityName)) || (province != null && !"".equals(province)))) {
            return cityOpenList.getCityId(cityName, province);
        }
        return null;
    }

    CustomDialog.Builder builder;

    void showSwitch() {
        if (builder == null)
            builder = new CustomDialog.Builder(mContext);
        builder.setMessage("您目前所在的城市为" + locationBox.getCityName());//设置显示的内容
        builder.setTitle("自动定位");
        builder.setPositiveButton("切换", new DialogInterface.OnClickListener() {//添加确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                City city = ApplicationHelper.getInstance().getCity();
                city.setCityId(locationBox.getCityId());
                city.setCityName(locationBox.getCityName());
                ApplicationHelper.getInstance().updateCity(city);
                Intent main = new Intent(HomeActivity.this, HomeActivity.class);
                main.putExtra("cityId", locationBox.getCityId());
                main.putExtra("cityName", locationBox.getCityName());
                startActivity(main);
//                homeFragment.requestHome(locationBox.getCityId(), locationBox.getCityName(), null, null,true);todo
                DataManager.getInstance().isNeedRefreshCart = true;
                DataManager.getInstance().setCartCnt(0);
                DataManager.getInstance().clearCart();
                onCartCountChange(0);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
                //showRedBagDialog();
            }

        });
        builder.create().show();
    }

    private void initLocation() {

        locationService = new LocationService(getApplicationContext());

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
        ) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    0x1991);
        } else if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
        ) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    0x1993);
        } else {
            locationService.start();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0x1993:
            case 0x1991: {
                // If requestSilent is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    locationService.start();
                } else {
//                    toast("位置权限获取失败");
                }
                return;
            }

        }
    }


    public boolean isTopFragmentVisible() {
//        if(homeFragment != null && currentIndex == 0 && homeFragment.getCurrentIndex() == 0){
//            return true;
//        }todo

        return false;
    }

    public void updateCategoryStatus(String marketId, String topCategoryId, String categoryId, String nameId) {

//        List<String> marketIds = new ArrayList<>();
//        if (marketId != null){
//            marketIds.add(marketId);
//        }
//
//        if (goodsFragment == null) {
//            goodsFragment = new CategoryGoodsFragment();
//            goodsFragment.updateStatus(marketIds,topCategoryId,categoryId,nameId);
//            FragmentManager fm = getSupportFragmentManager();
//
//            FragmentTransaction transaction = fm.beginTransaction();
//            transaction.add(R.id.content, goodsFragment, TAG_CATEGORY_FRAGMENT);
//            if (homeFragment != null) {
//                transaction.hide(homeFragment);
//            }
//            if (cartFragment != null) {
//                transaction.hide(cartFragment);
//            }
//            if (mineFragment != null) {
//                transaction.hide(mineFragment);
//            }
//            transaction.show(goodsFragment);
//            transaction.commit();
//
//        }else {
//            goodsFragment.updateStatus(marketIds,topCategoryId,categoryId,nameId);
//            goodsFragment.updateData(true);
//            updatePageStatus(1);
//        }
//
//        lyTab.setCurrentTab(1);

    }
}
